import { ipcRenderer } from "electron";

export default class SubwinIPCService {
  ipcHandler: Map<string, Set<any>>;

  constructor() {
    this.ipcHandler = new Map<string, Set<any>>();
    ipcRenderer.on("PluginSendMessageToParentWindow", (_event: any, ipcMsg: any) => {
      this.handleIPCMsg(ipcMsg);
    });
  }

  onBatch(events: any) {
    for (const eventName in events) {
      if (!this.ipcHandler.has(eventName)) {
        this.ipcHandler.set(eventName, new Set<any>());
      }
      const funSet = this.ipcHandler.get(eventName);
      if (!funSet) return;
      funSet.add(events[eventName]);
    }
  }

  offBatch(events: any) {
    for (const eventName in events) {
      if (!this.ipcHandler.has(eventName)) {
        continue;
      }
      const funSet = this.ipcHandler.get(eventName);
      if (!funSet) continue;
      funSet.delete(events[eventName]);
    }
  }

  handleIPCMsg(ipcMsg: any) {
    const eventName = ipcMsg.api;
    if (!eventName) {
      console.error("HandleIPC: No API Provided!", ipcMsg);
      return;
    }
    const funSet = this.ipcHandler.get(eventName);
    if (funSet) {
      for (const handler of funSet) {
        handler(ipcMsg);
      }
    }
  }

  sendIPCMsg(subWindowId: number, data: any) {
    ipcRenderer.send("PluginSendMessageToSubWindow",
      subWindowId,
      data
    );
  }
}
